package com.hzw.saas.common.flow.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzw.saas.common.flow.constants.FlowConsts;
import com.hzw.saas.common.flow.mapper.FlowProcessPermissionMapper;
import com.hzw.saas.common.flow.pojo.data.UserInfo;
import com.hzw.saas.common.flow.pojo.model.FlowProcessPermission;
import com.hzw.saas.common.flow.service.IFlowProcessPermissionService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author sonam
 * @since 2021-08-04
 */
@Service
public class FlowProcessPermissionServiceImpl extends ServiceImpl<FlowProcessPermissionMapper, FlowProcessPermission> implements IFlowProcessPermissionService {

    @Override
    public boolean checkFlowProcess(String flowProcessId, String flowSubmitUserId, UserInfo userInfo) {
        if (Objects.isNull(userInfo))
            userInfo = new UserInfo();
        LambdaQueryChainWrapper<FlowProcessPermission> query = this.getPermissionQuery(flowSubmitUserId, userInfo);
        int count = query
            .eq(FlowProcessPermission::getFlowProcessId, flowProcessId)
            .select(FlowProcessPermission::getFlowProcessId)
            .count();
        return count > 0;
    }

    @Override
    public List<String> filterFlowProcesses(List<String> flowProcessIds, String flowSubmitUserId, UserInfo userInfo) {
        if (Objects.isNull(userInfo))
            userInfo = new UserInfo();
        if(CollectionUtil.isEmpty(flowProcessIds)) {
            return new ArrayList<>();
        }
        LambdaQueryChainWrapper<FlowProcessPermission> query = this.getPermissionQuery(flowSubmitUserId, userInfo);
        List<FlowProcessPermission> list = query
            .in(FlowProcessPermission::getFlowProcessId, flowProcessIds)
            .select(FlowProcessPermission::getFlowProcessId)
            .list();
        return list.stream().map(FlowProcessPermission::getFlowProcessId).collect(Collectors.toList());
    }

    private LambdaQueryChainWrapper<FlowProcessPermission> getPermissionQuery(String flowSubmitUserId, UserInfo userInfo) {
        return super.lambdaQuery()
            .eq(StrUtil.isNotBlank(userInfo.getRoleId()), FlowProcessPermission::getRoleId, userInfo.getRoleId())
            .and(StrUtil.isNotBlank(userInfo.getUserId()), queryWrapper -> queryWrapper
                .eq(FlowProcessPermission::getUserId, userInfo.getUserId()).or()
                .eq(Objects.equals(userInfo.getUserId(), flowSubmitUserId), FlowProcessPermission::getUserId, FlowConsts.PERMISSION_SUBMIT_USERID));
    }
}
